/**
 * @author Mauro
 */
$(document).ready(function(){
    $('.editDialog').each(function(){
        createDialog($(this).attr('rel'),$(this).attr('rel'));
    });
});

function sendByAjax( module , action , varName , data , idDivResponse ) {
    $.ajax({
        url: '?module='+module+'&ajax=1&display=0&action='+action,
        type: 'POST',
        data: varName+'='+data,
        beforeSend: function() {
            $('#'+idDivResponse).addClass('loading').text('');
        },
        success: function(response) {
            $('#'+idDivResponse).removeClass('loading').text(response);
        }
    });
}
 
function createAjaxForms() {
	var model = arguments[0];
	
	$("#form"+model).ajaxForm({
		beforeSubmit: function() {
			var vReturn = $("#form"+model).validate().form();
			if(vReturn)
			{
				showMask();
				$("#edit"+model).dialog("close");
				return true;
			}
			else
				return false;
		},
		success: function() {
			updateAllModel(model);
			hideMask();
		}
	});
}

function createDialog() {
	var model = arguments[0];
	var module = arguments[1];
	
	$("#edit"+model).dialog({
		position: ['center', 'center'],
		width: '700px',
		height: 650,
		modal: 	true,
		overlay: {
			backgroundColor: "#000000"
		},
		closeOnEscape: true,
		draggable: false,
		autoOpen: false,
		resizable: true,
		open: function() {
			var id = $(this).data('id');
			edit(model,module,id);
		}
	});
}

function buttonEdit() {
	var model = arguments[0];
	var id = (!arguments[1])?null:arguments[1];
	$("#edit"+model).data('id',id).dialog("open");
	return false;
}

function updateAllModel() {
	var model = arguments[0];
	var id_newsletter = $("#id_newsletter").val();
	$("#all"+model).html();
	$("#all"+model).addClass('loading');
    hideMask();
	$.ajax({
		url: "index.php",
		type: "GET",
		data: "module=boletin&action=all"+model+"&ajax=1&id_newsletter="+id_newsletter,
		success: function(data) {
			$("#all"+model).removeClass();
			$("#all"+model).addClass('caja');
			$("#all"+model).html(data);
		}
	});
}

function edit() {
	var model = arguments[0];
	var modulo = arguments[1];
	var id = (!arguments[2])?"":"&id="+arguments[2];
	$.ajax({
		beforeSend: showMask,
		url: "index.php",
		type: "GET",
		data: "module="+modulo+"&action=edit&ajax=1"+id,
		success: function(data) {
			$("#edit"+model).html(data);
			hideMask();
		}
	});
	return false;
}

function buttonDelete() {
	modulo = arguments[0];
	id = arguments[1];
	model = arguments[2];
	
	if(confirm('¿Estás seguro que quieres eliminar esto?'))
	{
		$.ajax({
			beforeSend: showMask,
			url: "index.php",
			type: "GET",
			data: "module="+modulo+"&action=delete&id="+id,
			success: function(data) {
				updateAllModel(model);
				hideMask();
			}
		});
	}
	return false;
}